package com.authine.cloudpivot.web.api.controller;

import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectQueryModel;
import com.authine.cloudpivot.engine.component.query.api.FilterExpression;
import com.authine.cloudpivot.engine.component.query.api.Page;
import com.authine.cloudpivot.engine.component.query.api.helper.PageableImpl;
import com.authine.cloudpivot.engine.component.query.api.helper.Q;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.service.ExecutionPlanService;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import com.authine.cloudpivot.web.api.vo.ExecutionPlan;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * @ClassName ZXJHController
 * @Description 执行计划接口
 * @Author cp
 * @Date 2021/10/22
 */
@Api(description = "外企德科相关接口", tags = "执行计划")
@RestController
@RequestMapping("/api/zxjh")
@Slf4j
@Validated
@Component
public class ZXJHController extends BaseController {

    @Autowired
    private ExecutionPlanService executionPlanService;

    @ApiOperation(value = "生成客户信息")
    @PostMapping("/updateZXJH")
    @ResponseBody
    public ResponseResult<?> updateExecutionPlanList(@RequestParam("id") String id) {
        JSONObject json = new JSONObject();
        Long statusReal = 200L;
        List<? extends BizObjectModel> changedContents = getChangedExecutionPlan(id);
        if (CollectionUtils.isNotEmpty(changedContents)) {
            String subjectName = (String)((HashMap)changedContents.get(0).getData().get("subjectName")).get("id");
            if (StringUtils.isNotEmpty(subjectName)) {
                List<? extends BizObjectModel> originalContents = getOriginalExecutionPlan(subjectName);
                if (CollectionUtils.isNotEmpty(originalContents) && StringUtils.isNotEmpty(originalContents.get(0).getId())) {
                    updateExecutionPlan(originalContents, changedContents);
                    json.put("message", "更新执行计划成功");
                    return ResponseResult.<JSONObject>builder().errcode(statusReal).data(json).build();
                } else {
                    statusReal = 500L;
                    json.put("message", "更新执行计划失败：执行计划为空");
                    return ResponseResult.<JSONObject>builder().errcode(statusReal).data(json).build();
                }
            } else {
                json.put("message", "更新执行计划失败：项目未关联");
                return ResponseResult.<JSONObject>builder().errcode(statusReal).data(json).build();
            }
        } else {
            json.put("message", "更新执行计划失败：执行计划变更未创建成功");
            return ResponseResult.<JSONObject>builder().errcode(statusReal).data(json).build();
        }
    }

    private void updateExecutionPlan(List<? extends BizObjectModel> originalContents, List<? extends BizObjectModel> changedContents) {
        String parentId = originalContents.get(0).getId();
        List<Map<String, Object>> changedPlans = (List<Map<String, Object>>) changedContents.get(0).getData().get("changedExecutionPlan");
        List<ExecutionPlan> executionPlans = new ArrayList<>();
        ExecutionPlan executionPlan = null;
        for (Map<String, Object> changedPlan : changedPlans) {
            executionPlan = new ExecutionPlan();
            String id = UUID.randomUUID().toString().replaceAll("-", "");
            executionPlan.setId(id);
            executionPlan.setPlanType((String) changedPlan.get("planType"));
            executionPlan.setPlanName((String) changedPlan.get("planName"));
            executionPlan.setPlanContent((String) changedPlan.get("planContent"));
            executionPlan.setStartTime((Date) changedPlan.get("changedStartTime"));
            executionPlan.setEndTime((Date) changedPlan.get("changedEndTime"));
            executionPlan.setParentId(parentId);
            executionPlan.setSortkey((BigDecimal)changedPlan.get("sortKey"));
            executionPlan.setModifier(this.getUserId());
            executionPlan.setModifiedTime((Date) changedPlan.get("modifiedTime"));
            executionPlans.add(executionPlan);
        }
        executionPlanService.delExecutionPlanByParentId(parentId);
        executionPlanService.insertExecutionPlans(executionPlans);
    }

    private List<? extends BizObjectModel> getChangedExecutionPlan(String id) {
        // 查询对应的位置id
        BizObjectQueryModel queryModel = new BizObjectQueryModel();
        PageableImpl pageable = new PageableImpl(0, 9999);
        queryModel.setSchemaCode("execute_plan_update");
        queryModel.setQueryCode("execute_plan_update");
        queryModel.setPageable(pageable);
        FilterExpression filterExpression = Q.it("id", FilterExpression.Op.Eq, id);
        queryModel.setFilterExpr(filterExpression);
        Page<BizObjectModel> executionPlanPages = getBizObjectFacade().queryBizObjects(queryModel);
        List<? extends BizObjectModel> changedContents = executionPlanPages.getContent();
        return changedContents;
    }

    private List<? extends BizObjectModel> getOriginalExecutionPlan(String projectName) {
        // 查询对应的位置id
        BizObjectQueryModel queryModel = new BizObjectQueryModel();
        PageableImpl pageable = new PageableImpl(0, 9999);
        queryModel.setSchemaCode("execute_plan");
        queryModel.setQueryCode("execute_plan");
        queryModel.setPageable(pageable);
        FilterExpression filterExpression = Q.it("subjectName", FilterExpression.Op.Eq, projectName);
        queryModel.setFilterExpr(filterExpression);
        Page<BizObjectModel> executionPlanPages = getBizObjectFacade().queryBizObjects(queryModel);
        List<? extends BizObjectModel> originalContents = executionPlanPages.getContent();
        return originalContents;
    }

}
